package com.ccit.springbootlaw.controller.base;

import com.ccit.springbootlaw.controller.resful.Code;
import com.ccit.springbootlaw.controller.resful.Result;
import com.ccit.springbootlaw.pojo.Root;
import com.ccit.springbootlaw.service.RootService;
import com.ccit.springbootlaw.utils.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/roots")
public class RootController {

    @Autowired
    private RootService rootService;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    /**
     * 根据ID查询管理员
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable int id) {
        Root root = rootService.findById(id);
        if (root != null) {
            return new Result(Code.GET_OK, root, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "查询失败，未找到管理员");
        }
    }

    /**
     * 根据传入实体进行多条件查询的方法（其中对用户名进行模糊查询）
     */
    @PostMapping("/search")
    public Result findByRootWithUsernameLike(@RequestBody Root root) {
        List<Root> roots = rootService.findByRootWithUsernameLike(root);
        if (roots != null && !roots.isEmpty()) {
            return new Result(Code.GET_OK, roots, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "查询失败，未找到符合条件的管理员");
        }
    }

    /**
     * 根据用户名或ID查询管理员，并验证密码
     */
    @PostMapping("/login")
    public Result findByUsernameOrIdAndPassword(@RequestBody Root temp) {
        String text = temp.getName();
        String password = temp.getPassword();
        int id = 0;
        // 增加对纯数字的校验
        if (text.matches("\\d+")) {
            id = Integer.parseInt(text);
        }
        Root root = rootService.findByUsernameOrIdAndPassword(text, id, password);
        if (root != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", root.getId());
            claims.put("userName", root.getName());
            claims.put("userRole", root.getRole());
            String token = JWTutil.generateToken(claims);
            //令牌存到redis中
            stringRedisTemplate.opsForValue().set(token, token, 1, TimeUnit.DAYS);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userId", root.getId());
            data.put("userRole", root.getRole());
            data.put("userName", root.getName());
            data.put("userEmail", root.getEmail());
            return new Result(Code.LOGIN_OK, data, "登录成功");
        } else {
            return new Result(Code.LOGIN_ERR, null, "登录失败，用户名或密码错误");
        }
    }

    /**
     * 插入新的管理员
     */
    @PostMapping("/enroll")
    public Result insertRoot(@RequestBody Root root) {
        // 检查用户名和邮箱是否已存在
        Root existingRootByName = rootService.findByUsernameOrIdAndPassword(root.getName(), 0, null);
        Root existingRootByEmail = rootService.findByUsernameOrIdAndPassword(null, 0, root.getEmail());
        if (existingRootByName != null || existingRootByEmail != null) {
            return new Result(Code.ADD_ERR, null, "用户名或邮箱已存在");
        }
        int result = rootService.insertRoot(root);
        if (result > 0) {
            return new Result(Code.ADD_OK, root, "添加成功");
        } else {
            return new Result(Code.ADD_ERR, null, "添加失败");
        }
    }

    /**
     * 更新管理员信息
     */
    @PutMapping
    public Result updateRoot(@RequestBody Root root, @RequestHeader("Authorization") String token) {
        // 检查用户名和邮箱是否已存在
        Root existingRootByName = rootService.findByUsernameOrIdAndPassword(root.getName(), 0, null);
        Root existingRootByEmail = rootService.findByUsernameOrIdAndPassword(null, 0, root.getEmail());
        if (existingRootByName != null || existingRootByEmail != null) {
            return new Result(Code.UPDATE_ERR, null, "用户名或邮箱已存在");
        }

        // 更新管理员信息
        int result = rootService.updateRoot(root);
        if (result > 0) {
            if (root.getPassword() != null && stringRedisTemplate.opsForValue().get(token).equals(token)) {
                stringRedisTemplate.delete(token);
            }
            return new Result(Code.UPDATE_OK, root, "更新成功");
        } else {
            return new Result(Code.UPDATE_ERR, null, "更新失败");
        }
    }

    /**
     * 删除管理员
     */
    @DeleteMapping("/{id}")
    public Result deleteRootById(@PathVariable int id) {
        int result = rootService.deleteRootById(id);
        if (result > 0) {
            return new Result(Code.DELETE_OK, null, "删除成功");
        } else {
            return new Result(Code.DELETE_ERR, null, "删除失败");
        }
    }

    /**
     * 查询所有管理员
     */
    @GetMapping
    public Result findAllRoots() {
        List<Root> roots = rootService.findAllRoots();
        if (roots != null && !roots.isEmpty()) {
            return new Result(Code.GET_OK, roots, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "查询失败，未找到任何管理员");
        }
    }
}